﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.IO;
using System.Web;
using Com.Framework;
using System.Reflection;

namespace Com.Library.Page
{
	public class AjaxPageHelper
	{
		private JavaScriptSerializer serializer = new JavaScriptSerializer();

		private Dictionary<string, object> _RowParamFromRequest = null;

		private void SetRowParamFromRequest(HttpRequest request)
		{
			string requestValue = new StreamReader(request.InputStream).ReadToEnd();

			if (!string.IsNullOrEmpty(requestValue))
			{
				_RowParamFromRequest = serializer.Deserialize<Dictionary<string, object>>(requestValue);
			}
			else
			{
				_RowParamFromRequest = new Dictionary<string,object>();
			}
		}

		private object GetJsonValue( string Name )
		{
			return _RowParamFromRequest[ Name ];
		}

		public void OnPageLoad (WebPage page, HttpRequest request, HttpResponse response)
		{
			string clinetIP = request.UserHostAddress; 
			string urlReferer = request.UrlReferrer != null? request.UrlReferrer.ToString().ToLower() : string.Empty;

			SetRowParamFromRequest(request);

			string vb = request.QueryString["_vb"].Parse(string.Empty);

			Type type = page.GetType();
			MethodInfo method = type.GetMethod( vb );

			if (method != null)
			{
				object[] parameterVals = new object[ method.GetParameters().Length ];

				int i = 0;

				foreach(ParameterInfo param in method.GetParameters())
				{
					parameterVals[i] = Convert.ChangeType( GetJsonValue( param.Name ), param.ParameterType );
					i++;
				}

				object obj = method.Invoke(page, parameterVals);

				string s = "{\"d\":" + serializer.Serialize(obj) + "}";
				response.ContentType = "application/json";
				if (s != null)
				{
					response.Clear();
					response.Write(s);
					response.Flush();
					response.End();
				}
			}
		}
	}
}
